package chaincodeInfo

import (
	"fmt"
	pb "github.com/hyperledger/fabric-protos-go/peer"
	lcpackager "github.com/hyperledger/fabric-sdk-go/pkg/fab/ccpackager/lifecycle"
)

// 链码信息
type ChaincodeInfo struct {
	Name     string
	Path     string
	Version  string // 默认为1.0  升级链码则为2.0，之后类推
	Sequence int64  // 默认为1  更新链码则+1
	// pkg、pkgId、label： 知道label、pkg-->pkgId    知道pkgId-->pkg
	Label string //默认为：Name+ "_" +Version
	Pkg   []byte // 打包后的链码包
	PkgID string
	// 注意：
	//1、链码语言  暂时默认为Go语言
	//CCType int
	// 类型
	//  ChaincodeSpec_UNDEFINED ChaincodeSpec_Type = 0
	//	ChaincodeSpec_GOLANG    ChaincodeSpec_Type = 1
	//	ChaincodeSpec_NODE      ChaincodeSpec_Type = 2
	//	ChaincodeSpec_CAR       ChaincodeSpec_Type = 3
	//	ChaincodeSpec_JAVA      ChaincodeSpec_Type = 4
	// 2、默认背书策略
}

// New 新建链码实例
func New(name string, path string) *ChaincodeInfo {
	Chaincode := &ChaincodeInfo{
		Name:     name,
		Path:     path,
		Version:  "1.0",
		Sequence: 1,
		Label:    name + "_1.0",
		Pkg:      nil,
	}
	return Chaincode
}

// NewAlreadyRunningChaincode 创建已经安装的链码实例
func NewAlreadyRunningChaincode(name string, path string, version string, sequence int64, label string) *ChaincodeInfo {
	Chaincode := &ChaincodeInfo{
		Name:     name,
		Path:     path,
		Version:  version,
		Sequence: sequence,
		Label:    label,
		Pkg:      nil,
	}
	return Chaincode
}

// PackageCC 打包链码
func (c *ChaincodeInfo) PackageCC() error {
	desc := &lcpackager.Descriptor{
		Path:  c.Path,
		Type:  pb.ChaincodeSpec_GOLANG,
		Label: c.Label,
	}
	ccPkg, err := lcpackager.NewCCPackage(desc)
	if err != nil {
		return fmt.Errorf("Package chaincode source error: %v", err)
	}
	c.Pkg = ccPkg
	// 获取PkgId
	c.PkgID = lcpackager.ComputePackageID(c.Label, ccPkg)
	return nil
}
